//
//  PAChartConfigManager.m
//  PilotSeries
//
//  Created by 黄立强 on 16/6/29.
//  Copyright © 2016年 leon.huang. All rights reserved.
//

#import "PAChartConfigManager.h"
#import "FMDB.h"
#import "ChartConfig.h"
/** 数据库实例 */
static FMDatabase *_db;
@implementation PAChartConfigManager

+ (void)initialize
{
    // 1.获得数据库文件的路径
    NSString *doc = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
    NSString *filename = [doc stringByAppendingPathComponent:@"pilot.sqlite"];
    
    // 2.得到数据库
    _db = [FMDatabase databaseWithPath:filename];
    
    // 3.打开数据库
    if ([_db open]) {
        // 4.创表
        BOOL result = [_db executeUpdate:@"CREATE TABLE IF NOT EXISTS t_chartConfig (id integer PRIMARY KEY AUTOINCREMENT, username text NOT NULL,env integer NOT NULL,chartname text NOT NULL,chart_config blob NOT NULL);"];
        if (result) {
            LOG(@"成功创表")
        } else {
            LOG(@"创表失败")
        }
    }
}

+(NSArray *)loadCurrentChartConfigsByUserName:(NSString *)username withEnv:(NSInteger )env{
    
    FMResultSet *resultSet = nil;
    // 创建数组缓存微博数据
    NSMutableArray *configs = [NSMutableArray array];
    resultSet = [_db executeQuery:@"SELECT * FROM t_chartConfig WHERE username = ? AND env = ? ;",username,@(env)];
    // 遍历查询结果
    while (resultSet.next) {
        ChartConfig  *chartConfig = [ChartConfig new];
        NSData *config = [resultSet objectForColumnName:@"chart_config"];
        NSString *chartName = [resultSet stringForColumn:@"chartname"];
//        NSString *rangeName = [resultSet stringForColumn:@"rangename"];
        NSDictionary *configDict = [NSKeyedUnarchiver unarchiveObjectWithData:config];
        chartConfig.chartName = chartName;
        chartConfig.config = configDict;
//        chartConfig.rangeName =rangeName;
        [configs addObject:chartConfig];
        
    }
    
    return configs;
}

+(ChartConfig *)loadCurrentChartConfigByChartName:(NSString *)chartName withUsername:(NSString *)username withEnv:(NSInteger )env {
    
    FMResultSet *resultSet = nil;
    resultSet = [_db executeQuery:@"SELECT * FROM t_chartConfig WHERE username = ? AND env = ? AND chartname = ?;",username,@(env),chartName];
    ChartConfig  *chartConfig = nil;
    // 遍历查询结果
    while (resultSet.next) {
        chartConfig = [ChartConfig new];
        NSData *config = [resultSet objectForColumnName:@"chart_config"];
        NSString *chartName = [resultSet stringForColumn:@"chartname"];
//         NSString *rangeName = [resultSet stringForColumn:@"rangename"];
        NSDictionary *configDict = [NSKeyedUnarchiver unarchiveObjectWithData:config];
        chartConfig.chartName = chartName;
        chartConfig.config = configDict;
//        chartConfig.rangeName =rangeName;
        
    }
    
    
    return chartConfig;
}

+(ChartConfig *)loadCurrentChartConfigByChartName:(NSString *)chartName{
    
    return [self loadCurrentChartConfigByChartName:chartName withUsername:[PAAppContext sharedInstance].username withEnv:[PAAppContext sharedInstance].envType];
}

+(NSArray *)loadCurrentChartConfigs{
    
    return  [self loadCurrentChartConfigsByUserName:[PAAppContext sharedInstance].username withEnv:[PAAppContext sharedInstance].envType];

}

+(void)saveCurrentChartConfigs:(NSArray *) chartConfigs withUserName:(NSString *)username withEnv:(NSInteger )env{
    if ([_db open]) {
        [_db beginTransaction];
        BOOL isRollBack = NO;
        @try {
            //1.删除当前用户之前所有的chartConfigs
            [self deleteCurrentChartConfigsWithUsername:username withEnv:env];
            
            for (ChartConfig *chartConfig in chartConfigs) {
                NSData *data =[NSKeyedArchiver archivedDataWithRootObject:chartConfig.config];
                [_db executeUpdate:@"INSERT INTO t_chartConfig (username, chartname, chart_config,env) VALUES (?, ?, ?,?);",username,chartConfig.chartName,data,@(env)];
            }
        } @catch (NSException *exception) {
            
            isRollBack = YES;
            [_db rollback];
        } @finally {
            if (!isRollBack) {
                [_db commit];
            }
            
        }
        
    }
   
    
}


+(void)saveCurrentChartConfigs:(NSArray *) chartConfigs{
    NSString *username = [PAAppContext sharedInstance].username;
    NSInteger env = [PAAppContext sharedInstance].envType;
   [self saveCurrentChartConfigs:chartConfigs withUserName:username withEnv:env];
    
}

+(void)saveCurrentChartConfigsUseMerge:(NSArray *) chartConfigs withUserName:(NSString *)username withEnv:(NSInteger )env{
    
    if ([_db open]) {
        [_db beginTransaction];
         BOOL isRollBack = NO;
        @try {
            for (ChartConfig *chartConfig in chartConfigs) {
                
                [self saveChartConfig:chartConfig withUserName:username withEnv:env];
            }
            
        } @catch (NSException *exception) {
            isRollBack = YES;
            [_db rollback];
        } @finally {
            if (!isRollBack) {
                [_db commit];
            }
        }
    }
    
  
    
    
}
+(void)saveCurrentChartConfigsUseMerge:(NSArray *) chartConfigs{
//    NSString *username = [PAAppContext sharedInstance].username;
//    NSInteger env = [PAAppContext sharedInstance].envType;
    [self saveCurrentChartConfigsUseMerge:chartConfigs];
    
    
}
+(BOOL)saveChartConfig:(ChartConfig *) chartConfig withUserName:(NSString *)username withEnv:(NSInteger )env{
    
   ChartConfig *loadChartConfig = [self loadCurrentChartConfigByChartName:chartConfig.chartName withUsername:username withEnv:env ];
    NSData *data =[NSKeyedArchiver archivedDataWithRootObject:chartConfig.config];
    BOOL dflag;
    if (loadChartConfig!=nil) {
        //update
        dflag =  [_db executeUpdate:@"UPDATE t_chartConfig set chart_config = ? where username = ? AND env = ? AND chartname = ?",data,username,@(env),chartConfig.chartName];
    }else{
        dflag =   [_db executeUpdate:@"INSERT INTO t_chartConfig (username, chartname, chart_config,env) VALUES (?, ?, ?,?);",username,chartConfig.chartName,data,@(env)];
    }
    if (dflag) {
        LOG(@"saveCurrentChartConfig success!")
    }else{
        DDLogError(@"saveCurrentChartConfig fail!");
    }
    return loadChartConfig!=nil;
}

+(BOOL)saveChartConfig:(ChartConfig *) chartConfig{
    
    NSString *username = [PAAppContext sharedInstance].username;
    NSInteger env = [PAAppContext sharedInstance].envType;
   return [self saveChartConfig:chartConfig withUserName:username withEnv:env];
    
}

+(void)deleteCurrentChartConfigByChartName:(NSString *) chartName withUserName:(NSString *)username withEnv:(NSInteger )env{
    ChartConfig *loadChartConfig = [self loadCurrentChartConfigByChartName:chartName withUsername:username withEnv:env ];
    if (loadChartConfig!=nil) {
        BOOL result =  [_db executeUpdate:@"DELETE FROM t_chartConfig where username = ? AND env = ? AND chartname = ?",username,@(env),chartName];
        if (result) {
            LOG(@"deleteCurrentChartConfigByChartName success!")
        }else{
            DDLogError(@"deleteCurrentChartConfigByChartName fail!");
        }
    }else{
         DDLogError(@"user:%@ -->env:%ld -->chartName:%@ is not exists!",username,env,chartName);
    }
    
}

+(void)deleteCurrentChartConfigByChartName:(NSString *) chartName{
    NSString *username = [PAAppContext sharedInstance].username;
    NSInteger env = [PAAppContext sharedInstance].envType;
    [self deleteCurrentChartConfigByChartName:chartName withUserName:username withEnv:env];
}

+(void)deleteCurrentChartConfigsWithUsername:(NSString *)username withEnv:(NSInteger )env{
    
    BOOL result =  [_db executeUpdate:@"DELETE FROM t_chartConfig where username = ? AND env = ?",username,@(env)];
    if (result) {
        LOG(@"deleteCurrentChartConfigsWithUsername success!")
    }else{
        DDLogError(@"deleteCurrentChartConfigsWithUsername fail!");
    }
    
}

+(void)deleteCurrentChartConfigs{
    NSString *username = [PAAppContext sharedInstance].username;
    NSInteger env = [PAAppContext sharedInstance].envType;
    [self deleteCurrentChartConfigsWithUsername:username withEnv:env];
}

+(void)updateChartConfig:(ChartConfig *) chartConfig{
    
    NSString *username = [PAAppContext sharedInstance].username;
    NSInteger env = [PAAppContext sharedInstance].envType;
    NSData *data =[NSKeyedArchiver archivedDataWithRootObject:chartConfig.config];
    BOOL dflag;
    dflag =  [_db executeUpdate:@"UPDATE t_chartConfig set chart_config = ? where username = ? AND env = ? AND chartname = ?",data,username,@(env),chartConfig.chartName];
    if (dflag) {
        LOG(@"updateChartConfig success!")
    }else{
        DDLogError(@"updateChartConfig fail!");
    }
}

+(BOOL)isExistInCurrentChart:(NSString *)chartName{
    
    ChartConfig  *chartConfig = [self loadCurrentChartConfigByChartName:chartName];
    if (chartConfig!=nil) {
        return YES;
    }
    return NO;
}
@end
